# -*- coding: utf-8 -*-
import codecs
import os
import mp3play 
import time
import threading
import tempfile
import shutil

resource_folder = unicode(os.path.normpath(os.path.join(os.path.dirname(__file__), "../res")))
pdict = {} 
pfile = codecs.open(os.path.join(resource_folder, "pinyin.txt"), "r", "utf-8")
for line in pfile.read().splitlines():
    mandarin, pinyin = line.split('|')
    pdict[mandarin] = pinyin.split(' ')
  
def play_sound(filepath):
    def play_async(filepath):
        sound = mp3play.load(filepath)
        sound.play()
        while sound.isplaying():
            time.sleep(0.1)
    
    dummy, ext = os.path.splitext(filepath)
    temp = tempfile.mktemp(suffix=ext)
    shutil.copy(filepath, temp)
    t = threading.Thread(target=play_async, args=(temp, ))
    t.start()
    
def pinyin(mandarin):
    out = []
    for ch in mandarin: 
        out.append(pdict[ch])
    return out

def pinyin_fmt(mandarin):
    words = pinyin(mandarin)
    out = []
    for options in words:
        out.append(options[0] + '?' if len(options) > 1 else '')
    return ' '.join(out)

def tts_sync(mandarin):
    words = pinyin(mandarin).split(' ')
    for n, word in enumerate(words):
        mp3path = os.path.join(resource_folder, u'pinyin', word.lower() + '.mp3')
        mp3 = mp3play.load(mp3path)
        mp3.play()
        time.sleep(0.1)
        while mp3.isplaying():
            time.sleep(0.1)

def tts(mandarin):
    t = threading.Thread(target=tts_sync, args=(mandarin, ))
    t.start()

if __name__ == '__main__':
    pass